<template>
  <div class="user">
    <!-- 面包屑导航-->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-row>
        <el-col :span="7">
          <el-input clearable placeholder="请输入内容" v-model="queryInfo.query">
            <el-button slot="append" icon="el-icon-search" @click="sousuo"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4"
          ><div class="grid-content bg-purple-light">
            <el-button @click="addUser">添加用户</el-button>
          </div></el-col
        >
      </el-row>

      <el-table el-table--scrollable-x el-table--scrollable-y border ref="singleTable" :data="userList" highlight-current-row style="width: 100%">
        <el-table-column type="index" label="序号" :index="serialNum" width="50"> </el-table-column>
        <el-table-column prop="username" label="姓名" width="120"></el-table-column>
        <el-table-column prop="username" label="姓名" width="120"></el-table-column>
        <el-table-column prop="username" label="姓名" width="120"></el-table-column>
        <el-table-column prop="username" label="姓名" width="120"></el-table-column>
        <el-table-column prop="username" label="姓名" width="120"></el-table-column>
        <el-table-column prop="username" label="姓名" width="120"></el-table-column>
        <el-table-column prop="username" label="姓名" width="120"></el-table-column>
        <el-table-column prop="username" label="姓名" width="120"></el-table-column>
        <el-table-column prop="username" label="姓名" width="120"></el-table-column>
        <el-table-column prop="username" label="姓名" width="120"></el-table-column>
        <el-table-column prop="username" label="姓名" width="120"></el-table-column>
        <el-table-column prop="username" label="姓名" width="120"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="120"></el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            {{ scope.row }}
            <el-switch v-model="scope.row.mg_state" @change="CheckState(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column property="" label="操作">
          <template slot-scope="scope">
            <!-- 编辑按钮 -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row.id)"></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRoleDialog(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 end-->

      <!-- 添加用户的对话框 -->
      <el-dialog title="添加用户" :visible.sync="addUserDialog" width="50%">
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addUserDialog = false">取 消</el-button>
          <el-button type="primary" @click="addUserSave">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑 start-->
      <el-dialog title="修改用户信息" :visible.sync="dialogFormVisible">
        <el-form :model="editForm">
          <el-form-item label="用户名" :label-width="formLabelWidth">
            <el-input disabled v-model="editForm.username"></el-input>
          </el-form-item>
          <el-form-item label="手机" :label-width="formLabelWidth">
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" :label-width="formLabelWidth">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveEdit">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 编辑 EEEE  end-->

      <!-- 分配角色 start   -->
      <el-dialog title="分配角色" :visible.sync="Rouledialog">
        <el-form :model="userInfo">
          <el-form-item label="用户名" :label-width="formLabelWidth">
            <el-input disabled v-model="userInfo.username"></el-input>
          </el-form-item>
          <el-form-item label="当前角色" :label-width="formLabelWidth">
            <el-input disabled v-model="userInfo.role_name"></el-input>
          </el-form-item>
          <el-form-item label="分配角色" :label-width="formLabelWidth">
            <el-select v-model="selectedRoleId" placeholder="请选择">
              <el-option v-for="item in roleDescList" :key="item.id" :label="item.roleName" :value="item.id"> </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="Rouledialog = false">取 消</el-button>
          <el-button type="primary" @click="saveUserRoulr(userInfo.id)">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 分配角色 EEEEend -->
      <!-- 分页 start -->
      <div class="block">
        <el-pagination
          layout="prev, pager, next,total, sizes"
          :page-sizes="[1, 2, 5, 10]"
          :page-size="queryInfo.pagesize"
          :total="total"
          :current-page="queryInfo.pagenum"
          @current-change="handleCurrentChange"
          @size-change="sizeChange"
        >
        </el-pagination>
      </div>
      <!-- 分页 end -->
    </el-card>
  </div>
</template>
<script>
export default {
  data() {
    return {
      total: 0,
      value: true,
      queryInfo: {
        query: '', //查询条件
        pagenum: 1, // 当前的页数
        pagesize: 2 // 当前每页显示多少条数据
      },
      userList: [],
      roleDescList: [],
      dialogFormVisible: false,
      Rouledialog: false,
      addUserDialog: false, //添加弹框
      editForm: {},
      userInfo: {},
      addForm: {
        //         username: '',
        // password: '',
        // email: '',
        // mobile: ''
      }, //添加表单
      formLabelWidth: '120px',
      selectedRoleId: '', // 已选中的角色Id值
      // 添加表单的验证规则对象
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '用户名的长度在3~10个字符之间',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '用户名的长度在6~15个字符之间',
            trigger: 'blur'
          }
        ],
        email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }],
        mobile: [{ required: true, message: '请输入手机号', trigger: 'blur' }]
      }
    }
  },
  methods: {
    sousuo() {
      //搜索
      this.getUsers()
    },
    //获取用户列表
    getUsers() {
      this.$http
        .get('users', { params: this.queryInfo })
        .then(result => {
          if (result.data.meta.status != 200) return this.$message.err('获取用户信息失败')
          this.userList = result.data.data.users
          this.total = result.data.data.total
        })
        .catch(err => {
          console.log(err)
        })
    },
    //状态修改
    CheckState(userinfo) {
      this.$http
        .put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
        .then(result => {
          if (result.data.meta.status !== 200) {
            userinfo.mg_state = !userinfo.mg_state
            return this.$message.error('更新用户状态失败！')
          }
          this.$message.success('更新用户状态成功！')
        })
        .catch(err => {
          console.log(err)
        })
    },
    addUser() {
      //添加用户
      this.addUserDialog = true
      console.log(this.addForm)
    },

    addUserSave() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        this.$http
          .post('users', this.addForm)
          .then(result => {
            if (result.data.meta.status !== 201) {
              return this.$message.error('添加失败')
            }
            this.$message.success('添加成功')
            this.addUserDialog = false
            this.addForm = {}
            this.getUsers()
          })
          .catch(err => {
            console.log(err)
          })
      })
    },

    //编辑 --获取用户信息
    showEditDialog(id) {
      this.$http
        .get(`users/${id}`)
        .then(result => {
          if (result.data.meta.status !== 200) {
            return this.$message.error('获取用户状态失败！')
          }
          this.editForm = result.data.data
        })
        .catch(err => {
          console.log(err)
        })
      this.dialogFormVisible = true
    },
    //编辑提交保存
    saveEdit() {
      this.$http
        .put(`users/${this.editForm.id}`, {
          email: this.editForm.email,
          mobile: this.editForm.mobile
        })
        .then(result => {
          if (result.data.meta.status !== 200) {
            return this.$message.error('提交失败！')
          }
          this.$message.success('更新成功')
          this.dialogFormVisible = false
        })
        .catch(err => {
          console.log(err)
        })
    },
    //删除 是否确定删除
    removeUserById(id) {
      console.log(id)
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.deleteUser(id)
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    },
    //删除方法
    deleteUser(id) {
      this.$http
        .delete(`users/${id}`)
        .then(result => {
          if (result.data.meta.status !== 200) {
            return this.$message.error('删除失败！')
          }
          this.$message.success('删除成功')
          this.getUsers()
        })
        .catch(err => {
          console.log(err)
        })
    },
    //分配权限 -- 弹框
    setRoleDialog(userData) {
      this.userInfo = userData

      this.$http
        .get(`roles`)
        .then(result => {
          if (result.data.meta.status !== 200) {
            return this.$message.error('获取列表失败！')
          }
          this.roleDescList = result.data.data
        })
        .catch(err => {
          console.log(err)
        })
      this.Rouledialog = true
    },

    //分配权限 保存角色信息
    saveUserRoulr(id) {
      this.$http
        .put(`users/${id}/role/`, {
          id: id,
          rid: this.selectedRoleId
        })
        .then(result => {
          if (result.data.meta.status !== 200) {
            console.log(result.data)
            return this.$message.error('更新用户状态失败！')
          }
          this.$message.success('更新用户状态成功！')
          this.Rouledialog = false
          this.getUsers()
        })
        .catch(err => {
          console.log(err)
        })
    },

    /**********分页方法 SSS************** */
    //添加序号
    serialNum(index) {
      return (this.queryInfo.pagenum - 1) * this.queryInfo.pagesize + index + 1
    },
    //每页条数改变
    sizeChange: function(n) {
      this.queryInfo.pagesize = n
      //console.log(n)
      this.getUsers()
    },
    // 监听 页码值 改变的事件 直接点第几页
    handleCurrentChange(newPage) {
      console.log(newPage)
      this.queryInfo.pagenum = newPage
      this.getUsers()
    }
    /**********分页方法 EEEE************** */
  },
  created() {
    this.getUsers()
  }
}
</script>
<style lang="less" scoped>
.tableX .el-table--scrollable-x .el-table__body-wrapper {
  padding: 0 0 5px 0;
  margin: 0 0 5px 0;
  overflow-x: auto;
}
  // 滚动条的宽度
  .el-table__body{
    width: 900px;
  }
  .el-table__header-wrapper{
    width: 1300px;
    overfLow-y: auto ;
  }
 .el-table__body-wrapper::-webkit-scrollbar {
    width: 6px; // 横向滚动条
    height: 6px; // 纵向滚动条 必写
  }
  // 滚动条的滑块
  .el-table__body-wrapper::-webkit-scrollbar-thumb {
    background-color: #ddd;
    border-radius: 3px;
  }

.slot::-webkit-scrollbar{
    width: 2px;
}
.slot::-webkit-scrollbar-thumb{
    border-radius: 2px;
    height: 50px;
    background: #eee;
}
.slot::-webkit-scrollbar-track{
    box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    border-radius: 2px;
    background: rgba(0,0,0,0.4);
}


</style>
